package com.mingqijia.gassafety.console.controller.inner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gap.basic.base.CommonResponse;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.ReceiverValve;
import com.mingqijia.gassafety.db.entity.redis.LatestLog;
import com.mingqijia.gassafety.db.mapper.FieldTemplateMapper;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.RecordLogRequest;
import com.mingqijia.gassafety.webserver.request.inner.*;
import com.mingqijia.gassafety.webserver.response.AlertLogResponse;
import com.mingqijia.gassafety.webserver.response.BrokenLogResponse;
import com.mingqijia.gassafety.webserver.response.client.*;
import com.mingqijia.gassafety.webserver.response.inner.IotskDtuResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.webserver.response.workorder.asst.LoopInfoResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.webserver.service.zj.ZjWifiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangfei
 * @version 1.0.0
 * @ClassName DeviceController.java
 * @createTime 2022年02月21日
 */
@RestController(value = "WorkOrderEquipment")
@Api(tags = "内部接口-设备管理")
@RequestMapping("/inner/v1")
@Slf4j
public class EquipmentController {

    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private ZjWifiService zjWifiService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    LatestLogService latestLogService;
    @Autowired
    FieldTemplateMapper fieldTemplateMapper;

    @Autowired
    CustomerSubsHistoryService subsHistoryService;

    @Autowired
    ConfigureHolder holder;

    @Autowired

    ReceiverValveService receiverValveService;

    @Autowired
    HistoryAlarmService historyAlarmService;

    @Autowired
    HistoryBrokenService historyBrokenService;

    @Autowired
    HistoryLogService historyLogService;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    /**
     * 设备信息详情
     * @return
     */
    @GetMapping("/asst/order/equipmentInfo")
    @ApiOperation(value = "根据imei查询设备信息")
    public CommonResponse<LoopInfoResponse> equipmentInfo(@RequestParam("iMEI")
                                                         String iMEI) {
        log.info(iMEI);
        return CommonResponse.success(equipmentService.equipmentInfo(iMEI,1));
    }

    /**
     * 多设备回路点位数
     * @return
     */
    @PostMapping("/asst/order/loopAmount")
    @ApiOperation(value = "多设备回路点位数")
    public CommonResponse<Map<String,Integer>> loopAmount(@RequestBody @Valid  LoopAmountRequest request) {
        log.info(request.toString());
        return CommonResponse.success(equipmentService.loopAmount(request));
    }

    /**
     * 紫荆WiFi报警器-创建和绑定
     * @return
     */
    @PostMapping("/zj/create/bind")
    @ApiOperation(value = "紫荆WiFi报警器-创建和绑定")
    public CommonResponse<Map<String,Integer>> createBind(@RequestBody @Valid ZJCreateBindRequest request) {
        log.info("紫荆WiFi报警器-创建和绑定" + request.toString());
        zjWifiService.createConsumerBindZJ(request);
        return CommonResponse.success(null);
    }

    /**
     * 紫荆WiFi报警器-解绑
     * @return
     */
    @PostMapping("/zj/unbind")
    @ApiOperation(value = "紫荆WiFi报警器-解绑")
    public CommonResponse<Map<String,Integer>> createUnbind(@RequestBody @Valid ZJUnBindRequest request) {
        log.info(request.toString());
        zjWifiService.unbindEquipment(request);
        return CommonResponse.success(null);
    }

    /**
     * 紫荆WiFi报警器-设备上报数量
     * @return
     */
    @PostMapping("/zj/data/count")
    @ApiOperation(value = "紫荆WiFi报警器-设备上报数量")
    public CommonResponse<Integer> dataCount(@RequestBody @Valid ZJDataCountRequest request) {
        log.info(request.toString());
        Integer count = zjWifiService.dataCount(request);
        CommonResponse res = CommonResponse.success(count);
        log.info("设备上报数量结果："+res.toString());
        return res;
    }

    @ApiOperation("报警器列表(for kitchen)")
    @PostMapping(value = "/alarm/list")
    public CommonResponse<List<IotskDtuResponse>> equipmentListForIotSk(@RequestBody @Valid InnerDtuListRequest request) {
        log.info("equipmentList for iot-sk  request: {}", request);
        CommonResponse<List<IotskDtuResponse>> dtus = null;
        try {
            List<IotskDtuResponse> dtuResponses = null;
            //传入户号判断绑定情况
//            if (StringUtil.isNotEmpty(request.getSubsCode())) {
//                ClientDtuListRequest clientDtuListRequest = new ClientDtuListRequest();
//                BeanUtils.copyProperties(request,clientDtuListRequest);
//                subsHistoryService.isBindSus(clientDtuListRequest,request.getSpId());
//            }
            dtuResponses = equipmentService.clientDtuListIotSk(request);
            dtus = CommonResponse.success( dtuResponses );
        } catch (Exception e) {
            log.error("报警器列表失败，", e);
        }
        if (ObjectUtils.isEmpty(dtus)) {
            return CommonResponse.success(Collections.emptyList());
        }
        return dtus;
    }

    @ApiOperation("设备详情")
    @RequestMapping(value = {"alarm/detail"}, method = RequestMethod.GET)
    public CommonResponse<ClientEquipmentDetailRes> detail(@RequestParam @ApiParam(value = "设备号") String imei){
        ClientEquipmentDetailRes res = new ClientEquipmentDetailRes();
        //设备基础信息
        LambdaQueryWrapper<Dtu> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Dtu::getIMEI,imei).eq(Dtu::getIsDeleted,0);
        Dtu equipment = equipmentService.getOne(queryWrapper);
        if (equipment == null) {
            return CommonResponse.failure("设备不存在");
        }
        BeanUtils.copyProperties(equipment,res);
        res.setDeviceId(equipment.getId());
        res.setImei(equipment.getIMEI());
        res.setEquipmentName(equipment.getName());
        //运营商
        if (!StringUtils.isEmpty(res.getOperators())) {
            DictionaryItemRespDTO operatorsDTO = holder.getDictionaryByKey(
                    Constants.OPERATOR_CODE, equipment.getSpId()).stream().filter(a -> a.getValue().equals(
                    res.getOperators())).collect(Collectors.toList()).get(0);
            res.setOperatorsName(operatorsDTO.getName());
        }
        //设备类型
        if (!StringUtils.isEmpty(res.getEquipmentType())) {
            DictionaryItemRespDTO equipmentTypeDict = holder.getDictionaryByKey(
                    EquipmentType.DICT_CODE, equipment.getSpId()).stream().filter(a->a.getValue().equals(
                    res.getEquipmentType())).collect(Collectors.toList()).get(0);
            res.setEquipmentTypeName(equipmentTypeDict.getName());
        }
        //设备厂商
        if (!StringUtils.isEmpty(res.getEquipmentManufacturer())) {
            //设备厂商名称
            ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", response);
            if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
                res.setEquipmentManufacturerName(response.getData().stream().filter(a->a.getAlarmSystemCode().equals(
                        equipment.getEquipmentManufacturer())).collect(Collectors.toList()).get(0).getMsName());
            }

        }
        //检测类型
        if (!StringUtils.isEmpty(res.getDetectionType())) {
            String detectionType = "";
            String[] detectionTypes = equipment.getDetectionType().split(";");
            for (String s : detectionTypes) {
                DictionaryItemRespDTO detectionTypeDict = holder.getDictionaryByKey(
                        Constants.DETECTION_TYPE_CODE, equipment.getSpId()).stream().filter(a->a.getValue().equals(
                        s)).collect(Collectors.toList()).get(0);
                detectionType = detectionType + detectionTypeDict.getName() + ";";
            }
            res.setDetectionType(detectionType);
        }
        //redis实时信息
        LatestLog latestLog = latestLogService.get(equipment.getIMEI(),equipment.getSpId());
        if (latestLog != null) {
            BeanUtils.copyProperties(latestLog,res);
        }
        //信号值
        if (res.getEquipmentStatus().equals(EquipmentStatus.offline)) {
            res.setSignal(SignalEnum.LEVEL_0.getLevel());
            res.setSignalStr(SignalEnum.LEVEL_0.getName());
        } else {
            res.setSignal(latestLog.getSignal());
            res.setSignalStr(latestLog.getSignalStr());
        }
        //查询控制器的点位数
        if (equipment.getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
            LambdaQueryWrapper<Dtu> pointWrapper = new LambdaQueryWrapper();
            pointWrapper.likeRight(Dtu::getIMEI,imei+"-").eq(Dtu::getIsDeleted,0);
            List<Dtu> pointList = equipmentService.list(pointWrapper);
            //去除控制器，剩余点位数
            res.setPoint(pointList.size());
        }
        if (res.getValidity() == null) res.setValidity(0);
        if (res.getExpirationTime() == null) res.setExpirationTime("");
        if (res.getEquipmentModel() == null) res.setEquipmentModel("");
        LambdaQueryWrapper<ReceiverValve> queryWrapper1 = new LambdaQueryWrapper();
        queryWrapper1.eq(ReceiverValve::getDeviceId,equipment.getId()).eq(ReceiverValve::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(ReceiverValve::getSpId, equipment.getSpId());
        ReceiverValve receiverValve = receiverValveService.getOne(queryWrapper1);
        log.info("alarm/detail receiverValve:", receiverValve);
        if (receiverValve != null) {
            BeanUtils.copyProperties(receiverValve,res);
        }
        return CommonResponse.success(res);
    }


    @ApiOperation("报警记录")
    @RequestMapping(value = {"alarm/alert"}, method = RequestMethod.GET)
    public CommonResponse<PageUtil<ClientAlertRes>> alertBrokenList(@RequestParam @ApiParam(value = "设备号") String imei,
                                                                    @RequestParam @ApiParam(value = "页数") Integer page,
                                                                    @RequestParam @ApiParam(value = "条数") Integer pageSize){
        List<ClientAlertRes> resultList = new ArrayList<>();
        //设备基础信息
        LambdaQueryWrapper<Dtu> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Dtu::getIMEI,imei).eq(Dtu::getIsDeleted,0);
        Dtu equipment = equipmentService.getOne(queryWrapper);
        if (equipment == null) {
            return CommonResponse.failure("设备不存在");
        }
        if (EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(equipment.getEquipmentType())) {
            return CommonResponse.success(new PageUtil(page, pageSize,0,new ArrayList()));
        }
        RecordLogRequest req = new RecordLogRequest();
        req.setImei(imei);
        req.setSpId(equipment.getSpId());
        req.setPage(page);
        req.setPageSize(pageSize);
        req.setTemplateType(TemplateTypeEnum.TEMPLATE_TYPE_1.getCode());
        PageUtil<AlertLogResponse> pageUtil = historyAlarmService.getAlarmList(req);
        for (AlertLogResponse alertLogResponse : pageUtil.getList()) {
            ClientAlertRes res = new ClientAlertRes();
            res.setImei(alertLogResponse.getImei());
            res.setEventTime(alertLogResponse.getLatestTime());
            res.setEquipmentManufacturer("报警");
            res.setEventInfo("");
            resultList.add(res);
        }
        PageUtil pageInfo = new PageUtil(req.getPage(), req.getPageSize(), pageUtil.getTotal(), resultList);
        return CommonResponse.success(pageInfo);
    }

    @ApiOperation("故障记录")
    @RequestMapping(value = {"alarm/broken"}, method = RequestMethod.GET)
    public CommonResponse<PageUtil<ClientAlertRes>> brokenList(@RequestParam @ApiParam(value = "设备号") String imei,
                                                               @RequestParam @ApiParam(value = "页数") Integer page,
                                                               @RequestParam @ApiParam(value = "条数") Integer pageSize){
        List<ClientAlertRes> resultList = new ArrayList<>();
        //设备基础信息
        LambdaQueryWrapper<Dtu> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Dtu::getIMEI,imei).eq(Dtu::getIsDeleted,0);
        Dtu equipment = equipmentService.getOne(queryWrapper);
        if (equipment == null) {
            return CommonResponse.failure("设备不存在");
        }
        RecordLogRequest req = new RecordLogRequest();
        req.setImei(imei);
        req.setSpId(equipment.getSpId());
        req.setPage(page);
        req.setPageSize(pageSize);
        req.setTemplateType(TemplateTypeEnum.TEMPLATE_TYPE_1.getCode());
        PageUtil<BrokenLogResponse> pageUtil = historyBrokenService.getList(req);
        for (BrokenLogResponse brokenLogResponse : pageUtil.getList()) {
            ClientAlertRes res = new ClientAlertRes();
            res.setImei(brokenLogResponse.getImei());
            res.setEventTime(brokenLogResponse.getLatestTime());
            res.setEquipmentManufacturer("故障");
            res.setEventInfo(brokenLogResponse.getBrokenReason());
            resultList.add(res);
        }
        PageUtil pageInfo = new PageUtil(req.getPage(), req.getPageSize(), pageUtil.getTotal(), resultList);
        return CommonResponse.success(pageInfo);
    }

    @ApiOperation("报警浓度曲线")
    @RequestMapping(value = { "alarm/log"}, method = RequestMethod.GET)
    public CommonResponse<List<ConcentrationCurveRes>> historyLog(@RequestParam @ApiParam(value = "设备号") String imei,
                                                                  @RequestParam @ApiParam(value = "开始时间") String timeStart,
                                                                  @RequestParam @ApiParam(value = "结束时间") String timeEnd){
        if (StringUtils.isEmpty(imei)) return CommonResponse.failure("设备号不能为空！");
        if (StringUtils.isEmpty(timeStart)) return CommonResponse.failure("开始时间不能为空！");
        if (StringUtils.isEmpty(timeEnd)) return CommonResponse.failure("结束时间不能为空！");
        return CommonResponse.success(historyLogService.getConcentrationCurve(imei,timeStart,timeEnd));
    }

    /**
     * 紫荆WiFi报警器-设备绑定
     * @return
     */
    @PostMapping("/zj/device/register")
    @ApiOperation(value = "紫荆WiFi报警器-设备注册")
    public CommonResponse<Map<String,Integer>> deviceRregister(@RequestBody @Valid ZJDeviceRegisterRequest request) {
        log.info("紫荆WiFi报警器-设备注册" + request.toString());
        zjWifiService.deviceRregister(request);
        return CommonResponse.success(null);
    }

    /**
     * 紫荆WiFi报警器-设备绑定
     * @return
     */
    @PostMapping("/zj/device/bind")
    @ApiOperation(value = "紫荆WiFi报警器-设备绑定")
    public CommonResponse<Map<String,Integer>> deviceBind(@RequestBody @Valid ZJDeviceBindRequest request) {
        log.info("紫荆WiFi报警器-设备绑定" + request.toString());
        zjWifiService.deviceBind(request);
        return CommonResponse.success(null);
    }

    /**
     * 紫荆WiFi报警器-设备解绑
     * @return
     */
    @PostMapping("/zj/device/unbind")
    @ApiOperation(value = "紫荆WiFi报警器-设备解绑")
    public CommonResponse<Map<String,Integer>> deviceUnbind(@RequestBody @Valid ZJDeviceBindRequest request) {
        log.info("紫荆WiFi报警器-设备解绑" + request.toString());
        zjWifiService.deviceUnbind(request);
        return CommonResponse.success(null);
    }

    /**
     * 紫荆WiFi报警器-设备删除
     * @return
     */
    @PostMapping("/zj/device/remove")
    @ApiOperation(value = "紫荆WiFi报警器-设备删除")
    public CommonResponse<Map<String,Integer>> deviceRemove(@RequestBody @Valid ZJDeviceRegisterRequest request) {
        log.info("紫荆WiFi报警器-设备删除" + request.toString());
        zjWifiService.deviceRemove(request);
        return CommonResponse.success(null);
    }

    @ApiOperation("报警器列表根据设备号批量查询")
    @PostMapping(value = "/alarm/equipment/list")
    public CommonResponse<List<IotskDtuResponse>> alarmEquipmentListFor(@RequestBody @Valid ZJAlarmEquipmentRequest request) {
        log.info("紫荆WiFi报警器列表查询request: {}", request);
        CommonResponse<List<IotskDtuResponse>> dtus = null;
        try {
            List<IotskDtuResponse> dtuResponses = null;
            //传入户号判断绑定情况
//            if (StringUtil.isNotEmpty(request.getSubsCode())) {
//                ClientDtuListRequest clientDtuListRequest = new ClientDtuListRequest();
//                BeanUtils.copyProperties(request,clientDtuListRequest);
//                subsHistoryService.isBindSus(clientDtuListRequest,request.getSpId());
//            }
            dtuResponses = equipmentService.alarmEquipmentListFor(request);
            dtus = CommonResponse.success( dtuResponses );
        } catch (Exception e) {
            log.error("报警器列表失败，", e);
        }
        if (ObjectUtils.isEmpty(dtus)) {
            return CommonResponse.success(Collections.emptyList());
        }
        return dtus;
    }

}
